package com.mk.web.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

/**
 * Created by WangChen on 2018/11/27 16:43.
 */
public class MybatisUtil {

    private static Logger logger = Logger.getLogger(MybatisUtil.class);

    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static SqlSessionFactory factory = null;
    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            logger.error("初始化加载mybatis.xml异常:", e);
        }
    }

    public static SqlSession getSession(){
        if (threadLocal.get() == null){
            threadLocal.set(factory.openSession());
        }
        return threadLocal.get();
    }

    public static void closeSession(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null){
            sqlSession.close();
        }
        threadLocal.set(null);
    }
}
